package it.lefo.dateReminder.service;

import it.lefo.dateReminder.EventsInDateView;
import it.lefo.dateReminder.R;
import it.lefo.dateReminder.bo.ContactsRepository;
import it.lefo.dateReminder.helper.DbHelper;
import it.lefo.dateReminder.model.Contact;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ReminderThread extends Thread {

	private ReminderService reminderService;

	private String tag = ReminderThread.class.getSimpleName();

	private boolean running = false;

	int NOTIFICATION = R.string.local_service_started;
	int DELAY = 60000; // 1 min
	int PERIOD = 5000; // 5 sec

	public ReminderThread(ReminderService reminderService) {
		this.reminderService = reminderService;
	}

	@Override
	public void run() {

		running = true;
		while (running) {
			checkData();
			try {
				Thread.sleep(DELAY);
			} catch (Throwable t) {
				Log.d(ReminderThread.class.getSimpleName(), t.getMessage());
			}
		}

	}

	private DbHelper getDbh() {
		return new DbHelper(reminderService);
	}

	private NotificationManager getNotificationManager() {
		return (NotificationManager) reminderService
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	private List<Contact> getContactToSend() {
		Log.i(tag, "getContactToSend Start");
		// DB connection

		List<Contact> contacts = new ArrayList<Contact>();
		SQLiteDatabase db;
		ContactsRepository cntRepo;
		Date dtSelected = Calendar.getInstance().getTime();

		try {
			// db connection
			db = getDbh().getOrCreateDataBase();
			cntRepo = new ContactsRepository(db);
			// Get Current Events
			contacts = cntRepo.getAllBirthday(dtSelected);
		} catch (Exception e) {
			Log.e(tag,
					"Errore durante la connessione al db. Exc Message: "
							+ e.getMessage() + ". Exc StakTrace: "
							+ e.getStackTrace());
		}

		Log.i(tag, "getContactToSend End");
		return contacts;
	}

	private void checkData() {
		Log.i(tag, "checkData Start");

		List<Contact> contacts = getContactToSend();

		CharSequence message = null;
		if (contacts != null && !contacts.isEmpty()) {
			message = contacts.size() + " eventi in data odierna";
		} else {
			message = "Nessun Evento in data odierna";
		}

		sendNotification(message);

	}

	public void sendNotification(CharSequence message) {
		Log.i(tag, "sendNotification Start");

		// Set the icon, scrolling text and timestamp
		Notification notification = new Notification(R.drawable.calendar01,
				message, System.currentTimeMillis());

		// The PendingIntent to launch our activity if the user selects this
		// notification
		PendingIntent contentIntent = PendingIntent.getActivity(
				reminderService, 0, new Intent(reminderService,
						EventsInDateView.class), 0);

		// Set the info for the views that show in the notification panel.
		notification.setLatestEventInfo(reminderService,
				"Date Reminder Service", message, contentIntent);

		// Send the notification.
		getNotificationManager().notify(NOTIFICATION, notification);

		Log.i(tag, "sendNotification End");
	}

}
